package online.westonline.com.westonline.ui;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.easy.west.westclient.Constants;
import com.easy.west.westclient.api.constacts.bean.PersonBean;
import com.easy.west.westclient.api.constacts.event.FindPersonisBundleEvent;
import com.jaeger.library.StatusBarUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.callback.GetUserInfoCallback;
import cn.jpush.im.android.api.enums.ConversationType;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.GroupInfo;
import cn.jpush.im.android.api.model.UserInfo;
import de.hdodenhof.circleimageview.CircleImageView;
import online.westonline.com.westonline.MyApplication;
import online.westonline.com.westonline.R;
import online.westonline.com.westonline.base.BaseActivity;
import online.westonline.com.westonline.event.CreateConvEvent;
import online.westonline.com.westonline.utils.ContactsUtils;
import online.westonline.com.westonline.utils.QRCodeUtil;
import online.westonline.com.westonline.utils.ToastUtils;
import online.westonline.com.westonline.utils.UiUtlis;
import online.westonline.com.westonline.wedgit.AppBarStateChangeListener;

import static android.graphics.Bitmap.Config.ARGB_8888;

/**
 * 联系人详情
 */
public class OneContactActivity extends BaseActivity {
    @BindView(R.id.img_one_avator)
    CircleImageView imgOneAvator;
    @BindView(R.id.tv_one_top_name)
    TextView tvOneTopName;
    @BindView(R.id.top_constacts_bar)
    Toolbar topConstactsBar;
    @BindView(R.id.tv_one_contacts_name)
    TextView tvOneContactsName;
    @BindView(R.id.img_erweima)
    ImageView imgErweima;
    @BindView(R.id.ra_namelayout)
    RelativeLayout raNamelayout;
    @BindView(R.id.collapsing_layout)
    CollapsingToolbarLayout collapsingLayout;
    @BindView(R.id.my_appbar)
    AppBarLayout myAppbar;
    @BindView(R.id.tv_constacts_company)
    TextView tvConstactsCompany;
    @BindView(R.id.tv_one_contacts_phone)
    TextView tvOneContactsPhone;
    @BindView(R.id.tv_one_contacts_email)
    TextView tvOneContactsEmail;
    @BindView(R.id.tv_one_contacts_adress)
    TextView tvOneContactsAdress;
    @BindView(R.id.tv_one_contacts_partment)
    TextView tvOneContactsPartment;
    @BindView(R.id.li_call)
    LinearLayout liCall;
    @BindView(R.id.li_sendemail)
    LinearLayout liSendemail;
    @BindView(R.id.li_sendmssage)
    LinearLayout liSendmssage;
    @BindView(R.id.li_chat)
    LinearLayout liChat;
    @BindView(R.id.img_one_contact_head)
    CircleImageView imgOneContactHead;
    @BindView(R.id.li_parent_view)
    LinearLayout liParentView;
    @BindView(R.id.tv_sao)
    TextView tvSao;
    @BindView(R.id.btn_call)
    FloatingActionButton btnCall;
    @BindView(R.id.btn_email)
    FloatingActionButton btnEmail;
    @BindView(R.id.btn_msg)
    FloatingActionButton btnMsg;
    @BindView(R.id.btn_chat)
    FloatingActionButton btnChat;
    TextView tvDialogName;
    LinearLayout liProgressview;
    ImageView imgEq;
    TextView tvSave;
    ImageView imgEqhead;
    @BindView(R.id.tv_to_phone)
    TextView tvToPhone;
    @BindView(R.id.tv_to_department)
    TextView tvToDepartment;
    @BindView(R.id.tv_one_contacts_zuoji)
    TextView tvOneContactsZuoji;
    @BindView(R.id.tv_to_zuoji)
    TextView tvToZuoji;
    //实体自行替换
    private PersonBean info;
    private int nowColor;
    private Dialog dialog_eq;
    private Bitmap bitmap;
    private View view;
    private Bitmap img_avator_bitmap;
    private Conversation conversation;
    private boolean is_head_loadindown = false;

    @Override
    protected void initview() {
        //设置toolbar
        setSupportActionBar(topConstactsBar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        //设置部分控件隐藏
        tvOneTopName.setVisibility(View.GONE);
        imgOneAvator.setVisibility(View.GONE);
        liChat.setVisibility(View.GONE);
        dialog_eq = new Dialog(this);
        //初始化对话框
        initdialog();
        //获取Bitmap头像
        initavator();

        //初始化ui
        initui();

        initsession();
    }

    /**
     * 暂无头像
     */
    private void initavator() {
        JMessageClient.getUserInfo(info.getAccess_token(), new GetUserInfoCallback() {
            @Override
            public void gotResult(int i, String s, UserInfo userInfo) {
                if (i == 0) {
                    userInfo.getBigAvatarBitmap(new GetAvatarBitmapCallback() {
                        @Override
                        public void gotResult(int i, String s, Bitmap bitmap) {
                            if (i == 0) {
                                is_head_loadindown = true;
                                imgEqhead.setImageBitmap(bitmap);
                                img_avator_bitmap = toRoundBitmap(bitmap);
                                imgOneAvator.setImageBitmap(bitmap);
                                imgOneContactHead.setImageBitmap(bitmap);
                            }
                        }
                    });
                }
            }
        });
    }

    /**
     * 利用浮动工具窗代替
     */
    private void initdialog() {
        view = View.inflate(this, R.layout.eq_dialogview, null);
        dialog_eq.setContentView(view);
        dialog_eq.setCancelable(true);
        // 获得当前activity所在的window对象
        Window window = dialog_eq.getWindow();
        WindowManager m = this.getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高度
        WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值
        p.height = (int) (d.getHeight() * 0.5); // 高度设置为屏幕的0.6，根据实际情况调整
        p.width = (int) (d.getWidth() * 0.8); // 宽度设置为屏幕的0.65，根据实际情况调整
        window.setAttributes(p);
        tvDialogName = view.findViewById(R.id.tv_dialog_name);
        liProgressview = view.findViewById(R.id.li_progressview);
        imgEq = view.findViewById(R.id.img_eq);
        tvSave = view.findViewById(R.id.tv_save);
        imgEqhead = view.findViewById(R.id.img_eq_head);
    }

    //ui初始化
    private void initui() {
        //全局颜色
        //nowColor = randomColor.randomColor();
        nowColor = UiUtlis.RandomColor();
        //配置
        btnChat.setBackgroundTintList(ColorStateList.valueOf(nowColor));
        btnEmail.setBackgroundTintList(ColorStateList.valueOf(nowColor));
        btnCall.setBackgroundTintList(ColorStateList.valueOf(nowColor));
        btnMsg.setBackgroundTintList(ColorStateList.valueOf(nowColor));
        StatusBarUtil.setColor(OneContactActivity.this, nowColor, 0);
        tvConstactsCompany.setText("高博汇科");
        tvOneTopName.setText(info.getName());
        tvOneContactsName.setText(info.getName());
        tvOneContactsPhone.setText(info.getPhonenum());
        tvOneContactsPartment.setText(info.getDepartmentDTO().getName());
        tvOneContactsZuoji.setText(info.getTel());
        tvOneContactsEmail.setText(info.getEmail());
        //设置collspan背景随机色
        myAppbar.setBackgroundColor(nowColor);
        collapsingLayout.setContentScrimColor(nowColor);
    }

    //事件监听
    private void initsession() {
        //对appbar的折叠监听
        myAppbar.addOnOffsetChangedListener(new AppBarStateChangeListener() {
            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                if (state == State.EXPANDED) {
                    //展开状态
                    raNamelayout.setVisibility(View.VISIBLE);
                    imgOneContactHead.setVisibility(View.VISIBLE);
                    imgOneAvator.setVisibility(View.GONE);
                    tvOneTopName.setVisibility(View.GONE);
                    tvSao.setClickable(true);
                    tvSao.setVisibility(View.VISIBLE);
                    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                    getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_keyboard_backspace_white_24dp);
                    StatusBarUtil.setColor(OneContactActivity.this, nowColor, 0);
                } else if (state == State.COLLAPSED) {
                    StatusBarUtil.setColor(OneContactActivity.this, UiUtlis.getColor(R.color.colorAppTheme), 0);
                    //折叠状态
                    raNamelayout.setVisibility(View.GONE);
                    imgOneContactHead.setVisibility(View.GONE);
                    tvSao.setClickable(false);
                    imgOneAvator.setVisibility(View.VISIBLE);
                    tvOneTopName.setVisibility(View.VISIBLE);
                    topConstactsBar.setBackgroundColor(UiUtlis.getColor(R.color.colorAppTheme));
                    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                    getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_keyboard_arrow_left_blue_500_24dp);
                } else {
                    //中间状态
                    imgOneAvator.setVisibility(View.GONE);
                    tvOneTopName.setVisibility(View.GONE);
                    tvSao.setClickable(false);
                    tvSao.setVisibility(View.GONE);
                    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                    getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_keyboard_backspace_white_24dp);
                    topConstactsBar.setBackgroundColor(nowColor);
                    //改变状态栏
                    StatusBarUtil.setColor(OneContactActivity.this, nowColor, 0);
                }
            }
        });
        //sao
        tvSao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(QeActivity.class, false);
            }
        });
        //发送短信
        liSendmssage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //短信内容自行编辑
                ContactsUtils.doSendSMSTo(info.getPhonenum(), "", OneContactActivity.this);
            }
        });
        //拨打电话
        liCall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //拨打
                //ContactsUtils.callPhone(info.getPhone(),OneContactActivity.this);
                ContactsUtils.diallPhone(info.getPhonenum(), OneContactActivity.this);
            }
        });
        //邮件
        liSendemail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String emali = (String) info.getEmail();
                if (TextUtils.isEmpty(emali)) {

                    AlertDialog.Builder builder = new AlertDialog.Builder(OneContactActivity.this);
                    builder.setTitle("提示");
                    builder.setCancelable(false);
                    builder.setMessage("没有邮箱号码是否跳转到邮箱界面手动输入?");
                    builder.setNegativeButton("取消", null);
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ContactsUtils.doSendEmail("", OneContactActivity.this);
                        }
                    });
                    builder.show();
                    return;
                }
                //邮件
                ContactsUtils.doSendEmail(emali, OneContactActivity.this);
            }
        });
        //二维码生成
        imgErweima.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                bitmap = QRCodeUtil.createQRCodeBitmap(info.getPhonenum() + ":" + info.getName(), 1000);
                if (is_head_loadindown) {
                    bitmap = QRCodeUtil.createQRCodeBitmap(info.getPhonenum() + ":" + info.getName()
                            , 1000, img_avator_bitmap, 0.2f);
                }
                imgEq.setImageBitmap(bitmap);
                tvDialogName.setText(info.getName());
                dialog_eq.show();
            }
        });
        //保存二维码至本地
        tvSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveBitmap();
            }
        });
        //聊天界面
        liChat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chat();
                //startActivityWithBundle(ChatActivity.class,false,bundle);
            }
        });
        //添加联系人二连
        tvToPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ContactsUtils.savePeople(info.getPhonenum(),info.getName(),OneContactActivity.this);
            }
        });
        tvToZuoji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ContactsUtils.savePeople(info.getTel(),info.getName(),OneContactActivity.this);
            }
        });
        //部门查看警告
        tvToDepartment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putInt("id",info.getDepartmentDTO().getDid());
                startActivityWithBundle(DepInfoActivity.class,false,bundle);
            }
        });

    }

    /**
     * 圆形
     *
     * @param bitmap
     * @return
     */
    public Bitmap toRoundBitmap(Bitmap bitmap) {
        // 前面同上，绘制图像分别需要bitmap，canvas，paint对象
        bitmap = Bitmap.createScaledBitmap(bitmap, 400, 400, true);
        Bitmap bm = Bitmap.createBitmap(400, 400, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bm);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        // 这里需要先画出一个圆
        canvas.drawCircle(200, 200, 200, paint);
        // 圆画好之后将画笔重置一下
        paint.reset();
        // 设置图像合成模式，该模式为只在源图像和目标图像相交的地方绘制源图像
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, 0, 0, paint);
        return bm;
    }

    /**
     * 聊天
     */
    private void chat() {
        //获取会话
        String username = info.getAccess_token();
        conversation = JMessageClient.getSingleConversation(username);
        if (conversation == null) {
            //创建会话
            conversation = Conversation.createSingleConversation(username);
        }
        //前往聊天界面
        //未添加的功能
        //1.全体识别,@识别
        //2.草稿传递
        if (conversation.getType() == ConversationType.group) {
            //群实体
            GroupInfo groupInfo = (GroupInfo) conversation.getTargetInfo();
            //如果是群聊
            Bundle bundle = new Bundle();
            //群聊标记true
            bundle.putBoolean(Constants.MODE, true);
            //群聊id
            bundle.putLong(Constants.GROUP_ID, groupInfo.getGroupID());
            //启动到对应界面
            startActivityWithBundle(ChatActivity.class, false, bundle);
        } else {
            //用户实体
            UserInfo target_user = (UserInfo) conversation.getTargetInfo();
            //如果是单聊
            Bundle bundle = new Bundle();
            //单聊标记false
            bundle.putBoolean(Constants.MODE, false);
            //单聊id
            bundle.putString(Constants.SINGLE_ID, target_user.getUserName());
            //单聊要用的appkey
            bundle.putString(Constants.TARGET_APPKEY, target_user.getAppKey());
            //启动到对应界面
            startActivityWithBundle(ChatActivity.class, false, bundle);
        }
        //会话已创建
        EventBus.getDefault().post(new CreateConvEvent(conversation));
    }


    /**
     * 保存二维码
     */
    private void saveBitmap() {

        String path = Constants.CONSTACTS_HEAD;
        //先创建目录
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        try {
            File file1 = new File(path, info.getPhonenum() + "_er" + ".jpeg");
            FileOutputStream outputStream = new FileOutputStream(file1);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        ToastUtils.showToast("保存成功");
    }

    @Override
    protected void initdata() {
        info = (PersonBean) getIntent().getExtras().getSerializable("data");

        //查询是否绑定
        MyApplication.getClient().findConstactsisLink(info.getAid());
    }

    @Override
    protected int setlayout() {
        return R.layout.activity_one_contact;
    }

    /**
     * 从文件里取的宽度
     *
     * @param inSampleSize
     * @return
     */
    private BitmapFactory.Options getBitmapOption(int inSampleSize) {
        System.gc();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPurgeable = true;
        options.inSampleSize = inSampleSize;
        return options;
    }

    /**
     * drawable转bitmap
     *
     * @param drawable
     * @return
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        // 取 drawable 的长宽
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();

        // 取 drawable 的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? ARGB_8888
                : Bitmap.Config.RGB_565;
        // 建立对应 bitmap
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        // 建立对应 bitmap 的画布
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        // 把 drawable 内容画到画布中
        drawable.draw(canvas);
        return bitmap;
    }

    /**
     * 查看用户是否绑定
     *
     * @param eva
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void isBundle(FindPersonisBundleEvent eva) {
        if (eva.isOk()) {
            boolean isbundle = eva.getBean();
            if (isbundle) {
                liChat.setVisibility(View.VISIBLE);
            } else {
                Snackbar.make(topConstactsBar, "该用户还未绑定,不能直接发起任务和聊天", Snackbar.LENGTH_INDEFINITE).setActionTextColor(UiUtlis.getColor(R.color.BlueTheme)).setAction("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }).show();
            }
        }
    }


}
